import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { NestExpressApplication } from '@nestjs/platform-express';
import { Logger } from '@nestjs/common';
import { json } from 'express';
import * as helmet from 'helmet';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import * as path from 'path';
import express from 'express';

async function bootstrap() {
  // 设置默认时区
  dayjs.extend(utc);
  dayjs.extend(timezone);
  dayjs.tz.setDefault('Asia/Shanghai');

  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: ['log', 'debug', 'error', 'verbose', 'warn'],
  });

  app.use(helmet.default()); // 安全问题解决
  app.enableCors(); // 启用跨域
  app.use(json({ limit: '500mb' }));

  app.use('/uploads', express.static(path.join(__dirname, '..', 'uploads')));
  app.use('/export', express.static(path.join(__dirname, '..', 'export')));
  app.use('/template', express.static(path.join(__dirname, '..', 'template')));

  const options = new DocumentBuilder()
    .setTitle('系统-后端服务')
    .setDescription('系统-接口文档')
    .setVersion('1.0')
    .addBearerAuth({
      type: 'http',
      scheme: 'bearer',
      bearerFormat: 'JWT',
      in: 'header',
      name: 'Authorization',
      description: '请输入JWT格式的Bearer token到字段',
    })
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api-docs', app, document);

  process.on('error', error => {
    console.log(error);
  });

  // 监听服务端口
  await app.listen(process.env.SERVER_PORT).then(async () => {
    Logger.debug(`Port: ${process.env.SERVER_PORT}`, '服务启动');

    Logger.log(`OpenAPI: http://${process.env.SERVER_ADDRESS}:${process.env.SERVER_PORT}/api-docs`);
  });
}
bootstrap();
